import os
import json
import tkinter as tk
from tkinter import messagebox
import threading
import time
from ping_module import ping_ip
from tools import save_to_config, read_from_config, find_password  # 导入新的工具函数

 

# 全局变量，跟踪是否正在进行IP测试
is_testing_ip = False



def show_functions(right_frame, log_operation, log_text):
    global is_testing_ip
    for widget in right_frame.winfo_children():
        widget.destroy()
    
    right_frame.config(bg="white")

    # sn标签
    account_label = tk.Label(right_frame, text="SN:", font=("Arial", 20), bg="white")
    account_label.place(x=100, y=50)

    # SN输入框
    SN_entry = tk.Entry(right_frame, width=60, font=("Arial", 20), bd=2)  # 添加边框
    SN_entry.place(x=150, y=50, width=450, height=50)  # 调整x坐标，使输入框贴着标签的左侧

    checkbox_var = tk.IntVar()
    checkbox = tk.Checkbutton(right_frame, variable=checkbox_var, font=("Arial", 15), bg="white")
    checkbox.place(x=600, y=50, width=50)
    
    #自动标签
    label = tk.Label(right_frame, text="自动", font=("Arial", 20), bg="white")
    label.place(x=650, y=50, width=50, height=50)

    #开始按钮函数
    def on_start_button_click():
        sn_value = SN_entry.get().strip()  # 读取SN输入框的值并去除前后空格
        if not sn_value:  # 检查是否为空
            messagebox.showerror("错误", "SN不能为空")  # 弹窗提示
            return  # 停止执行
        else:
            password_value = find_password(sn_value)
            # 这里可以调用其他函数，具体内容待填充
            # log_operation(f"点击了“开始”按钮，SN值: {sn_value}")
            # 调用你要执行的函数，例如：
            # your_function(sn_value)

    #开始按钮
    start_button = tk.Button(right_frame, text="开始", font=("Arial", 15), width=400, height=50, command=on_start_button_click)
    start_button.place(x=150, y=120, width=450, height=50)

    #超时标签
    timeout_label = tk.Label(right_frame, text="ping超时时间:", font=("Arial", 15), bg="white")
    timeout_label.place(x=100, y=200)

    timeout_value = read_from_config("timeout")
    timeout_entry = tk.Entry(right_frame, width=10, font=("Arial", 20), bd=2)
    timeout_entry.place(x=250, y=200)
    if timeout_value is not None:
        timeout_entry.insert(0, str(timeout_value))

    def on_save_timeout():
        try:
            timeout = int(timeout_entry.get())
            if 10 <= timeout <= 999:
                text = f"保存ping超时时间: {timeout}s"
                save_to_config("timeout", timeout, log_text)
            else:
                messagebox.showerror("错误", "超时时间应在10到999之间。")
        except ValueError:
            messagebox.showerror("错误", "请输入有效的超时时间。")

    save_button = tk.Button(right_frame, text="保存", font=("Arial", 15), command=on_save_timeout)
    save_button.place(x=350, y=200)

    # 登录账号标签
    account_label = tk.Label(right_frame, text="登录账号:", font=("Arial", 15), bg="white")
    account_label.place(x=100, y=250)

    # 登录账号输入框
    account_entry = tk.Entry(right_frame, width=10, font=("Arial", 20), bd=2)
    account_entry.place(x=250, y=250)


    # 从 config.json 读取登录账号
    account_value = read_from_config("login_account")
    if account_value is not None:
        account_entry.insert(0, account_value)

    def on_save_account():
        account = account_entry.get()
        save_to_config("login_account", account, log_text)

    # 保存按钮
    account_save_button = tk.Button(right_frame, text="保存", font=("Arial", 15), command=on_save_account)
    account_save_button.place(x=350, y=250)

    def on_test_ip_button_click():
        global is_testing_ip
        if is_testing_ip:  # 如果当前正在测试IP，返回
            return

        ip = read_from_config("ip_address")  # 从config.json读取IP地址
        if ip is None:
            messagebox.showerror("错误", "未找到IP地址")
            return

        # 从 config.json 中读取超时时间
        timeout_value = read_from_config("timeout")

        if timeout_value is None:
            messagebox.showerror("错误", "未找到超时时间")
            return

        is_testing_ip = True  # 设置全局标志，表示当前正在进行IP测试
        test_ip_button.config(state=tk.DISABLED)  # 禁用按钮

        # 弹出正在 ping 的窗口
        popup = tk.Toplevel(right_frame)
        popup.title("正在ping")
        popup.geometry("300x100")

        ping_label = tk.Label(popup, text=f"正在ping {ip}...", font=("Arial", 14))
        ping_label.pack(pady=10)

        countdown_label = tk.Label(popup, text=f"{timeout_value}秒", font=("Arial", 14))
        countdown_label.pack(pady=10)

        # 用于控制是否继续执行 ping 和倒计时的标志
        stop_ping = False

        # 在用户关闭窗口时，停止ping操作并重新启用按钮
        def on_popup_close():
            nonlocal stop_ping
            stop_ping = True  # 标志设置为True表示停止ping
            popup.destroy()  # 销毁窗口
            right_frame.event_generate('<<EnableTestIpButton>>')  # 重新启用按钮

        # 绑定窗口关闭事件
        popup.protocol("WM_DELETE_WINDOW", on_popup_close)

        def ping_and_update():
            result = "请求超时"  # 默认值

            def countdown_with_ping(remaining_time):
                nonlocal result

                # 检查 popup 是否已经销毁
                if not popup.winfo_exists() or stop_ping:
                    return  # 如果窗口被销毁或者停止ping，则直接返回

                # 更新倒计时标签
                countdown_label.config(text=f"{remaining_time}秒")

                # 如果剩余时间大于 0
                if remaining_time > 0:
                    # 使用 after 方法，延迟 1 秒后继续倒计时
                    right_frame.after(1000, countdown_with_ping, remaining_time - 1)

                    # 检查是否 ping 通，放在单独的线程中进行
                    def check_ping():
                        if not stop_ping and ping_ip(ip):  # 检查是否ping成功，确保stop_ping为False
                            result = "已ping通"
                            if popup.winfo_exists():
                                popup.destroy()  # 关闭弹窗
                            messagebox.showinfo("结果", result)  # 显示测试结果
                            right_frame.event_generate('<<EnableTestIpButton>>')  # 重新启用按钮
                            return  # 如果ping成功，直接结束函数

                    # 启动一个新的线程来执行 ping_ip 检查
                    threading.Thread(target=check_ping).start()
                else:
                    # 倒计时结束，仍未 ping 通
                    if popup.winfo_exists():
                        popup.destroy()  # 关闭弹窗
                    messagebox.showinfo("结果", result)
                    right_frame.event_generate('<<EnableTestIpButton>>')  # 重新启用按钮

            # 启动倒计时并进行 ping 检查
            countdown_with_ping(timeout_value)

        # 启动 ping 线程，避免阻塞 GUI
        threading.Thread(target=ping_and_update).start()

        # 在绑定的事件处理器中重新启用按钮
        right_frame.bind('<<EnableTestIpButton>>', lambda event: test_ip_button.config(state=tk.NORMAL))
        is_testing_ip = False  # ping 完成后，重置标志








    test_ip_button = tk.Button(right_frame, text="测试ip", font=("Arial", 15), width=400, height=50, command=on_test_ip_button_click)
    test_ip_button.place(x=100, y=300, width=400, height=50)

    right_frame.bind('<<EnableTestIpButton>>', lambda event: test_ip_button.config(state=tk.NORMAL))
